package com.panda.aspect;

import com.panda.annotation.PageView;
import com.panda.utils.IpUtils;
import com.panda.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class PageViewAspect {

    @Autowired
    private RedisCache redisCache;

    /**
     * 切入处理
     *
     * @param joinPoint
     * @return
     */
    @Around("@annotation(com.panda.annotation.PageView)")
    public Object visitCount(ProceedingJoinPoint joinPoint) {
        PageView pageView = getPageView(joinPoint);
        String description = pageView.description();
        Object[] object = joinPoint.getArgs();
        Object id = object[0];
        log.info("id:{}", id);
        Object obj = null;
        String ipAddress = IpUtils.getIpAddr();
        log.info("ipAddress:{}", ipAddress);
        String key = "views:" + description + ":" + id;
        try {
            // 浏览量存入redis中
            Long num = redisCache.add(key, ipAddress);
            // if (num == 0) {
            // log.info("该ip:{},访问的浏览量已经新增过了", ipAddress);
            // }
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }


    private PageView getPageView(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod().getAnnotation(PageView.class);
    }
}
